package com.zhugang.week03;

import java.util.Stack;

/**
 * @program algorithms
 * @description: StackSequences
 * @author: chanzhugang
 * @create: 2022/06/05 17:08
 */
public class StackSequences {

    /**
     * 剑指offer31. 栈的压入、弹出序列
     * pushed = [1,2,3,4,5], poped = [4,5,3,2,1] -> true
     * pushed = [1,2,3,4,5], poped = [4,3,5,1,2] -> false
     *
     * @param pushed
     * @param poped
     * @return
     */
    public boolean isStackSequences(int[] pushed, int[] poped) {
        Stack<Integer> stack = new Stack<>();
        int i = 0;
        int j = 0;
        int k = 0;
        while (k < (pushed.length + poped.length)) {
            k++;
            // 出栈
            if (!stack.isEmpty() && j < poped.length && stack.peek() == poped[j]) {
                stack.pop();
                j++;
                continue;
            }
            // 入栈
            if (i < pushed.length) {
                stack.push(pushed[i]);
                i++;
                continue;
            }
            return false;
        }
        return true;
    }
}